<?php


namespace app\common\model;


use think\Config;

class Reservation extends BaseModel
{
    protected $name = "course_reservation";

    public function shop()
    {
        $module = static::getCalledModule() ?: 'common';
        return $this->BelongsTo("app\\{$module}\\model\\store\\Shop");
    }
    /**
     * 关联用户表
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        $module = static::getCalledModule() ?: 'common';
        return $this->BelongsTo("app\\{$module}\\model\\User");
    }

    public function course(){
        return $this->belongsTo('Course');
    }
    public function orderdetail(){
        $module = static::getCalledModule() ?: 'common';
        return $this->belongsTo("app\\{$module}\\model\\CourseOrderDetail",'course_order_id','course_order_id');
    }
    public function coach(){
        $module = static::getCalledModule() ?: 'common';
        return $this->BelongsTo("app\\{$module}\\model\\store\\shop\\Coach");
    }
    public function getWorkStatusAttr($value)
    {
        $status = [0 => '未发布作业', 1 => '已发布作业'];
        return ['text' => $status[$value], 'value' => $value];
    }
    public function usertask(){
        return $this->hasOne('UserTask','reservation_id','id');
    }
    /**
     * 获取订单详情
     * @param $where
     * @return static|null
     * @throws \think\exception\DbException
     */
    public static function detail($where)
    {
        return static::get($where,['usertask'=>['user','file','fileimage'],'course'=>['image','image.file'],'coach','coach.file','user','orderdetail']);
    }

    /**
     * @title 获取预约人数
     * @param $where
     * @author Qian
     * Time: 2023/3/18  15:39
     */
    public function getReservationCount($where){
        return $this->where($where)->count();
    }

    /**
     * @title分页获取预约记录
     * @param  $param
     * @author Qian
     * Time: 2023/2/28  15:12
     */
    public function getList($params = [],$order = ['create_time' => 'desc']){
        $params = array_merge([
            'shop_id'=>0,
            'user_id'=>0,
            'coach_id'=>0,
            'listRows'=>10,
            'date'=>'',
            'status'=>'',
            'start_time'=>'',
            'end_time'=>'',
            'course_type'=>''
        ],$params);

        $filter = [];
        $hasWhere = [];
        $params['course_type'] != '' && $hasWhere['type'] = $params['course_type'];
        $params['shop_id'] > 0 && $filter['Reservation.shop_id'] = $params['shop_id'];
        $params['user_id'] > 0 && $filter['user_id'] = $params['user_id']; //哪个用户预约的
        $params['coach_id'] > 0 && $filter['Reservation.coach_id'] = $params['coach_id']; //教练id
        is_array($params['coach_id']) && $filter['Reservation.coach_id'] = ['in',$params['coach_id']];//数组列表
        $params['date'] != '' && $filter['date'] = $params['date'];//预约的时间
        $params['status'] != '' && $filter['Reservation.status'] = $params['status'];//预约的课程的状态
        //时间筛选
//        $params['start_time'] != '' && $params['end_time'] == '' && $filter['create_time'] = ['egt',strtotime($params['start_time'])];
//        $params['start_time'] == '' && $params['end_time'] != '' && $filter['create_time'] = ['elt',strtotime($params['end_time'])];
//        $params['start_time'] != '' && $params['end_time'] != '' && $filter['create_time'] = ['between',[strtotime($params['start_time']),strtotime($params['end_time'])]];
        $params['start_time'] != '' && $params['end_time'] == '' && $filter['date'] = ['egt',$params['start_time']];
        $params['start_time'] == '' && $params['end_time'] != '' && $filter['date'] = ['elt',$params['end_time']];
        $params['start_time'] != '' && $params['end_time'] != '' && $filter['date'] = ['between',[$params['start_time'],$params['end_time']]];

        return self::hasWhere('course',$hasWhere)->with(['shop','user','course','course.image.file','coach','usertask'=>['file','fileimage']])
            ->where($filter)
            ->order($order)
            ->paginate($params['listRows'], false, [
                'query' => request()->request()
            ]);
    }

    public function getAllList($params = []){
        $params = array_merge([
            'shop_id'=>0,
            'coach_id'=>0,
            'listRows'=>10,
            'date'=>'',
            'status'=>'',
            'start_time'=>'',
            'end_time'=>'',
            'course_type'=>''
        ],$params);

        $filter = [];
        $hasWhere = [];
        $params['course_type'] != '' && $hasWhere['type'] = $params['course_type'];
        $params['shop_id'] > 0 && $filter['Reservation.shop_id'] = $params['shop_id'];
        $params['coach_id'] > 0 && $filter['Reservation.coach_id'] = $params['coach_id'];
        is_array($params['coach_id']) && $filter['Reservation.coach_id'] = ['in',$params['coach_id']];//数组列表
        $params['date'] != '' && $filter['date'] = $params['date'];//预约的时间
        $params['status'] != '' && $filter['Reservation.status'] = $params['status'];//预约的课程的状态
        $params['start_time'] != '' && $params['end_time'] == '' && $filter['date'] = ['egt',$params['start_time']];
        $params['start_time'] == '' && $params['end_time'] != '' && $filter['date'] = ['elt',$params['end_time']];
        $params['start_time'] != '' && $params['end_time'] != '' && $filter['date'] = ['between',[$params['start_time'],$params['end_time']]];

        return self::hasWhere('course',$hasWhere)->with(['shop','user','course','course.image.file','coach','coach.file','orderdetail'])
            ->where($filter)
            ->order(['create_time' => 'desc'])->select();
    }

    public function exportList($params){
        $list = $this->getAllList($params)->toArray();
        $title = [
//            '会员','手机号','日期','教练','门店','课程','课程卡(元)','次数','课时价','时间','状态',
            '会员','手机号','日期','教练','门店','课程','课程卡(元)','课时价','时间','状态',
        ];
        $status = Config::get('reservation');
        $data = [];
        foreach ($list as $k=>$v){
            $data[] = [
                '会员'=>$this->filterValue($v['user']['nickName']),
                '手机号'=>$this->filterValue($v['user']['phone']),
                '日期'=>$this->filterValue($v['start_time'] . '~' .substr($v['end_time'],-5)),
                '教练'=>$this->filterValue($v['coach']['real_name']),
                '门店'=>$this->filterValue($v['shop']['shop_name']),
                '课程'=>$this->filterValue($v['course']['course_name']),
                '课程卡'=>$this->filterValue($v['orderdetail']['total_price']),
//                '次数'=>$this->filterValue($v['orderdetail']['remain_nums'].'/'.$v['orderdetail']['nums']),
                '课时价'=>$this->filterValue(bcdiv($v['orderdetail']['total_price'],$v['orderdetail']['nums'])),
                '时间'=>$this->filterValue($v['create_time']),
                '状态'=>$this->filterValue($status[$v['status']]['name'])
            ];
        }
        $file_name = '预约记录-'.date('YmdHis').'.csv';
        export_excel($file_name,$title,$data);
    }

    private function filterValue($value)
    {
        return "\t" . $value . "\t";
    }

    public function getRemainList(){
        $filter['is_remain'] = 0;
        $filter['status'] = 0;//未上课
        $date = date('Y-m-d H:i:s');
        $filter['start_time'] = [['elt',date('Y-m-d H:i:s',strtotime("$date + 3 hour"))],['gt',$date],'and'];//未上课
        return $this->with(['shop','user','course','course.image.file','coach','coach.file','orderdetail'])->where($filter)
            ->order(['id' => 'asc'])->select();
    }

    /**
     * @title 取消预约
     * @param
     * @param
     * @author Qian
     * Time: 2023/3/14  16:26
     */
    public function CancelAppoint($user){
        $CourseOrderDetail = new CourseOrderDetail();
        $model = CourseOrderDetail::detail(['course_order_id'=>$this['course_order_id']]); //使用的课程卡
        if (!$this){
            $this->error = '预约记录不存在';
            return false;
        }
        if ($this['status'] == 1){
            $this->error = '上课中，不可取消';
            return false;
        }
        if ($this['status'] == 2){
            $this->error = '已下课，不可取消';
            return false;
        }
        if ($this['status'] == 3){
            $this->error = '此预约已取消';
            return false;
        }
        $coach = \app\common\model\store\shop\Coach::detail(['coach_id'=>$this['coach_id']]);
        if ($coach['user_id'] != $user['user_id']){
            $this->error = '此预约的课程不是你的';
            return false;
        }
        $now = time();
        if ($now >= strtotime($this['start_time']) && $now <= strtotime($this['end_time'])){
            $this->error = '上课中';
            return false;
        }
        if ($now >= strtotime($this['end_time'])){
            $this->error = '已下课了';
            return false;
        }
//        $reservation = $this;
        return $this->transaction(function () use ($model){
            $save['status'] = 3;//取消预约
            $this->allowField(true)->save($save);
            $order_save['remain_nums'] = ['inc',1];
            if ($model['card_status'] == 3){
                $order_save['card_status'] = 2;
            }
            $model->allowField(true)->save($order_save);
            return true;
        });

    }

    public function PubWork($data){
        if ($this['status'] != 2){
            $this->error = '此预约课程还没有下课';
            return false;
        }
        if ($this['work_status']['value'] == 1){
            $this->error = '已经发布过作业了';
            return false;
        }
        if ($data['work_title'] == '' || $data['work_content'] == ''){
            $this->error = '请输入作业的标题和内容';
            return false;
        }

        return $this->transaction(function ()use ($data){
            $save['work_title'] = $data['work_title'];
            $save['work_content'] = $data['work_content'];
            $save['work_status'] = 1;
            if (isset($data['sync_work']) && $data['sync_work'] == 1 && $this['course']['type']['value'] == 2){
                //团课 同步作业
                $sync_where['course_id'] = $this['course_id'];
                $sync_where['coach_id'] = $this['coach_id'];
                $sync_where['date'] = $this['date'];
//                $sync_where['type'] = 2;//团课
                $sync_where['work_status'] = 0; //未发布作业的
                self::where($sync_where)->update($save);
                return true;
            }else{
                $this->allowField(true)->save($save);
            }
            return true;
        });
//        if ($this->allowField(true)->save($data) !== false){
//            return  true;
//        }else{
//            return  false;
//        }
    }

    /**
     * @title 修改作业
     * @param $data
     * @author Qian
     * Time: 2023/5/29  9:14
     */
    public function EditWork($data){
        if ($this['status'] != 2){
            $this->error = '此预约课程还没有下课';
            return false;
        }
        if ($this['usertask'] != ''){
            $this->error = '该学员已经提交作业了，不可修改';
            return false;
        }
        if ($data['work_title'] == '' || $data['work_content'] == ''){
            $this->error = '请输入作业的标题和内容';
            return false;
        }

        return $this->transaction(function ()use ($data){
            $save['work_title'] = $data['work_title'];
            $save['work_content'] = $data['work_content'];
            if (isset($data['sync_work']) && $data['sync_work'] == 1 && $this['course']['type']['value'] == 2){
                //同步作业
                $sync_where['course_id'] = $this['course_id'];
                $sync_where['coach_id'] = $this['coach_id'];
                $sync_where['date'] = $this['date'];
                $sync_where['work_status'] = 1; //未发布作业的
                $list = self::where($sync_where)->select();
                $ids = [];
                foreach ($list as $k=>$v){
                    if ($v['usertask'] == ''){
                        array_push($ids,$v['id']);
                    }
                }
//                self::where($sync_where)->allowField(true)->save($data);
                self::whereIn('id',$ids)->update($save);
                return true;
            }else{

                $this->allowField(true)->save($save);
            }
            return true;
        });
//        if ($this->allowField(true)->save($save) !== false){
//            return  true;
//        }else{
//            return  false;
//        }
    }
}